package com.blb.order_service.service;

import com.blb.order_service.config.MyWXPayConfig;
import com.blb.order_service.sdk.WXPay;
import com.blb.order_service.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信支付Service
 */
@Service
public class PayService {

    /**
     * 下单
     * @param goodsId 商品id
     * @param price 价格
     * @return 二维码的URL
     */
    public Map<String, String> makeOrder(String goodsId, Long price) throws Exception {
        //创建支付对象
        MyWXPayConfig config = new MyWXPayConfig();
        WXPay wxPay = new WXPay(config);
        Map<String,String> map = new HashMap<>();
        map.put("appid",config.getAppID());
        map.put("mch_id",config.getMchID());
        map.put("device_info","WEB");
        map.put("nonce_str", UUID.randomUUID().toString().replace("-",""));
        map.put("body","商城购物");
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        map.put("out_trade_no", tradeNo);
        map.put("fee_type","CNY");
        map.put("total_fee",String.valueOf(price));
        map.put("notify_url","http://n538ep.natappfree.cc/order/notify"); //微信对商户后台的回调接口
        map.put("trade_type","NATIVE");
        map.put("product_id",goodsId);
        //执行统一下单
        Map<String, String> result = wxPay.unifiedOrder(map);
        System.out.println("result:"+result);
        //保存订单号
        result.put("trade_no",tradeNo);
        return result;
    }

    /**
     * 生成二维码
     * @param url
     * @param response
     */
    public void makeQRCode(String url, HttpServletResponse response){
        //通过支付链接生成二维码
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
            System.out.println("创建二维码完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查订单状态
     * @param tradeNo
     * @return
     * @throws Exception
     */
    public String checkOrder(String tradeNo) throws Exception {
        MyWXPayConfig config = new MyWXPayConfig();
        String str =
        "<xml>"+
           "<appid>"+config.getAppID()+"</appid>"+
            "<mch_id>"+config.getMchID()+"</mch_id>"+
            "<nonce_str>"+UUID.randomUUID().toString().replace("-","")+"</nonce_str>"+
            "<out_trade_no>"+tradeNo+"</out_trade_no>"+
            "<sign>5E00F9F72173C9449F802411E36208734B8138870ED3F66D8E2821D55B317078</sign>"+
        "</xml>";
        WXPay pay = new WXPay(config);
        Map<String,String> map = WXPayUtil.xmlToMap(str);
        Map<String, String> map2 = pay.orderQuery(map);
        String state = map2.get("trade_state");
        System.out.println("订单"+tradeNo+",状态"+state);
        return state;
    }

}
